package com.wu.llpsw.networking;

import com.wu.llpsw.networking.packet.C2SPacket;
import com.wu.llpsw.networking.packet.backYuanLiMaxPacket;
import com.wu.llpsw.networking.packet.backYuanLiNowPacket;
import com.wu.llpsw.networking.packet.huiFuYuanLi;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.network.simple.SimpleChannel;

public class ModMessage {
    private static SimpleChannel INSTANCE;

    private static int packetId = 0;
    private static int id(){
        return packetId++;
    }

    public static void register(){
        SimpleChannel net = NetworkRegistry.ChannelBuilder
                .named(new ResourceLocation("wu","messages"))
                .networkProtocolVersion(()->"1.0")
                .clientAcceptedVersions(s -> true)
                .serverAcceptedVersions(s -> true)
                .simpleChannel();

        INSTANCE = net;
        //请求服务器的包
        net.messageBuilder(C2SPacket.class,id(), NetworkDirection.PLAY_TO_SERVER)
                .decoder(C2SPacket::new)
                .encoder(C2SPacket::toBytes)
                .consumer(C2SPacket::handle)
                .add();
        //向服务器请求回复元力
        net.messageBuilder(huiFuYuanLi.class,id(), NetworkDirection.PLAY_TO_SERVER)
                .decoder(huiFuYuanLi::new)
                .encoder(huiFuYuanLi::toBytes)
                .consumer(huiFuYuanLi::handle)
                .add();

        //返回现在源力的包
        net.messageBuilder(backYuanLiNowPacket.class,id(),NetworkDirection.PLAY_TO_CLIENT)
                .decoder(backYuanLiNowPacket::new)
                .encoder(backYuanLiNowPacket::toBytes)
                .consumer(backYuanLiNowPacket::handle)
                .add();

        //返回最大源力的包
        net.messageBuilder(backYuanLiMaxPacket.class,id(),NetworkDirection.PLAY_TO_CLIENT)
                .decoder(backYuanLiMaxPacket::new)
                .encoder(backYuanLiMaxPacket::toBytes)
                .consumer(backYuanLiMaxPacket::handle)
                .add();
    }

    public static <MSG> void sendToServer(MSG message){
        INSTANCE.sendToServer(message);
    }

    public static <MSG> void sendToPlayer(MSG message, ServerPlayer player){
        INSTANCE.send(PacketDistributor.PLAYER.with(()-> player),message);
    }
}
